package com.gmrz.uas.plugin.uasextend;

import com.gmrz.uas.plugin.exception.PluginException;
import com.gmrz.uas.plugin.provider.ServiceProvider;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gongyuqiang on 2017/5/25.
 */
public class UASRestExtend implements RestExtendPlugin {
    private static final Logger LOG = LogManager.getLogger(UASRestExtend.class);
    protected ServiceProvider provider = null;

    @Override
    public String processPost(String request) throws PluginException{
        Map<String, String> resp = new HashMap<String, String>();
        if(provider != null){
            LOG.debug("begin to query from db");
            Connection conn = null;
            ResultSet rs = null;
            PreparedStatement s = null;
            resp.put("request", escapeHtmlAndScript(request));
            try {
                conn = provider.getUasConnection(true);
                s = conn.prepareStatement("select COUNT(1) as count from t_authenticators");
                rs = s.executeQuery();
                while (rs.next()) {
                    resp.put("users", escapeHtmlAndScript(rs.getString(1)));
                }
            }
            catch (SQLException e){
                throw new PluginException("Faild to query from db");
            }
            finally {
                //释放ResultSet
                if(rs != null){
                    try{
                        rs.close();
                    }
                    catch (Exception e){

                    }
                }
                //释放PreparedStatement
                if(s != null){
                    try{
                        s.close();
                    }
                    catch (Exception e){

                    }
                }
                //释放Conn
                if(conn != null){
                    try{
                        conn.close();
                    }
                    catch (Exception e){

                    }
                }

            }
        }
        Gson gson = new Gson();
        return gson.toJson(resp);
    }

    @Override
    public String processGet(String request) throws PluginException{
        return null;
    }

    @Override
    public void setServiceProvider(ServiceProvider provider) {
        this.provider = provider;
    }


    private static String escapeHtmlAndScript(String value) {
        if (null != value) {
            value = StringEscapeUtils.escapeHtml3(value);
            value = StringEscapeUtils.escapeHtml4(value);
            value = StringEscapeUtils.escapeEcmaScript(value);
        }
        return value;
    }
}
